package com.designoutput.ui
{
	import com.designoutput.enum.ToolType;
	import com.designoutput.event.CardEvent;
	import com.designoutput.event.CardLayerEvent;
	import com.designoutput.event.ColorPadEvent;
	import com.designoutput.event.MessageBoxEvent;
	import com.designoutput.event.SelectEvent;
	import com.designoutput.icon.CopyIcon;
	import com.designoutput.icon.CutIcon;
	import com.designoutput.icon.OpenIcon;
	import com.designoutput.icon.Optionbarbg;
	import com.designoutput.icon.OrderIcon;
	import com.designoutput.icon.PasteIcon;
	import com.designoutput.icon.PreviewIcon;
	import com.designoutput.icon.RedoIcon;
	import com.designoutput.icon.SaveIcon;
	import com.designoutput.icon.UndoIcon;
	import com.designoutput.manager.ClipboardManager;
	import com.designoutput.manager.ResourceManager;
	import com.designoutput.ui.controls.BarSplit;
	import com.designoutput.ui.controls.ColorPad;
	import com.designoutput.ui.controls.Dropdown;
	import com.designoutput.ui.controls.ToolButton;
	import com.designoutput.ui.newControls.MessageBox;
	import com.designoutput.ui.toolGroup.ExtensionsGroup;
	import com.designoutput.ui.toolGroup.HelpGroup;
	import com.designoutput.ui.toolGroup.ZoomGroup;
	import com.designoutput.ui.util.ColorPicker;
	import com.designoutput.utils.Globals;
	
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.filters.DropShadowFilter;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.net.navigateToURL;

	public class TopToolBar extends Sprite
	{
		private var _card:Card;
		private var _layer:CardFace;
				
		private var _at:ToolButton;

		private var _holder:Sprite;
		private var _backgroundBitmap:Bitmap;
		private var _cardTypesDropDown:Dropdown;
		private var _zoomGroup:ZoomGroup;
		private var _extensionsGroup:ExtensionsGroup;
		private var _helpGroup:HelpGroup;
		private var _backgroundColorPad:ColorPad;

		public function TopToolBar()
		{
			_backgroundBitmap = new Bitmap(new Optionbarbg(0, 0));
			_backgroundBitmap.filters = [ new DropShadowFilter(2, 45, 0, 0.5, 3, 3, 1, 2) ];
			addChild(_backgroundBitmap);

			// card type selection
			_cardTypesDropDown = new Dropdown(170, 170);
			_cardTypesDropDown.addEventListener(SelectEvent.COMMAND, cardTypesDropDown_changedHandler);
			_cardTypesDropDown.x = 20;
			_cardTypesDropDown.y = 9;
			addChild(_cardTypesDropDown);

			_holder = new Sprite();
			_holder.x = 0;
			_holder.y = 5;
			addChild(_holder);

			var split1:* = new BarSplit();
			split1.x = 205;
			split1.y = 1;
			_holder.addChild(split1);

			var open:ToolButton = new ToolButton(ToolType.Open, new OpenIcon(0, 0), 5, 5);
			open.addEventListener(MouseEvent.MOUSE_DOWN, tool_mouseDownHandler);
			open.addEventListener(MouseEvent.MOUSE_OVER, tool_mouseOverHandler);
			open.addEventListener(MouseEvent.MOUSE_OUT, tool_mouseOutHandler);
			open.addEventListener(MouseEvent.CLICK, open_clickHandler, false, 0, true);
			open.x = 215;
			open.y = 1;
			_holder.addChild(open);

			var save:ToolButton = new ToolButton(ToolType.Save, new SaveIcon(0, 0), 5, 5);
			save.addEventListener(MouseEvent.MOUSE_DOWN, tool_mouseDownHandler);
			save.addEventListener(MouseEvent.MOUSE_OVER, tool_mouseOverHandler);
			save.addEventListener(MouseEvent.MOUSE_OUT, tool_mouseOutHandler);
			save.addEventListener(MouseEvent.CLICK, saveButton_clickHandler, false, 0, true);
			save.x = 245;
			save.y = 1;
			_holder.addChild(save);

			var split2:* = new BarSplit();
			split2.x = 280;
			split2.y = 1;
			_holder.addChild(split2);

			var cut:ToolButton = new ToolButton(ToolType.Cut, new CutIcon(0, 0), 7, 6);
			cut.addEventListener(MouseEvent.MOUSE_DOWN, tool_mouseDownHandler);
			cut.addEventListener(MouseEvent.MOUSE_OVER, tool_mouseOverHandler);
			cut.addEventListener(MouseEvent.MOUSE_OUT, tool_mouseOutHandler);
			cut.addEventListener(MouseEvent.CLICK, cutButton_clickHandler, false, 0, true);
			cut.x = 290;
			cut.y = 1;
			_holder.addChild(cut);

			var copy:ToolButton = new ToolButton(ToolType.Copy, new CopyIcon(0, 0), 6, 5);
			copy.addEventListener(MouseEvent.MOUSE_DOWN, tool_mouseDownHandler);
			copy.addEventListener(MouseEvent.MOUSE_OVER, tool_mouseOverHandler);
			copy.addEventListener(MouseEvent.MOUSE_OUT, tool_mouseOutHandler);
			copy.addEventListener(MouseEvent.CLICK, copyButton_clickHandler, false, 0, true);
			copy.x = 320;
			copy.y = 1;
			_holder.addChild(copy);

			var paste:ToolButton = new ToolButton(ToolType.Paste, new PasteIcon(0, 0), 6, 5);
			paste.addEventListener(MouseEvent.MOUSE_DOWN, tool_mouseDownHandler);
			paste.addEventListener(MouseEvent.MOUSE_OVER, tool_mouseOverHandler);
			paste.addEventListener(MouseEvent.MOUSE_OUT, tool_mouseOutHandler);
			paste.addEventListener(MouseEvent.CLICK, pasteButton_clickHandler, false, 0, true);
			paste.x = 350;
			paste.y = 1;
			_holder.addChild(paste);

			var split3:BarSplit = new BarSplit();
			split3.x = 385;
			split3.y = 1;
			_holder.addChild(split3);

			var undo:ToolButton = new ToolButton(ToolType.Undo, new UndoIcon(0, 0), 6, 8);
			undo.addEventListener(MouseEvent.MOUSE_DOWN, tool_mouseDownHandler);
			undo.addEventListener(MouseEvent.MOUSE_OVER, tool_mouseOverHandler);
			undo.addEventListener(MouseEvent.MOUSE_OUT, tool_mouseOutHandler);
			undo.x = 395;
			undo.y = 1;
			_holder.addChild(undo);

			var redo:ToolButton = new ToolButton(ToolType.Redo, new RedoIcon(0, 0), 6, 8);
			redo.addEventListener(MouseEvent.MOUSE_DOWN, tool_mouseDownHandler);
			redo.addEventListener(MouseEvent.MOUSE_OVER, tool_mouseOverHandler);
			redo.addEventListener(MouseEvent.MOUSE_OUT, tool_mouseOutHandler);
			redo.x = 425;
			redo.y = 1;
			_holder.addChild(redo);

			var split4:BarSplit = new BarSplit();
			split4.x = 460;
			split4.y = 1;
			_holder.addChild(split4);

			_backgroundColorPad = new ColorPad(0xFFFFFF, true);
			_backgroundColorPad.addEventListener(MouseEvent.MOUSE_DOWN, backgroundColorPad_mouseDownHandler);
			_backgroundColorPad.addEventListener(ColorPadEvent.CHOOSE_COLOR, backgroundColorPad_colorChangeHandler);
			_backgroundColorPad.addEventListener(MouseEvent.MOUSE_OVER, showHover);
			_backgroundColorPad.addEventListener(MouseEvent.MOUSE_OUT, Globals.designoutputCard.hover.hideEvent);
			_backgroundColorPad.x = 475;
			_backgroundColorPad.y = 2;
			_holder.addChild(_backgroundColorPad);

			var split5:BarSplit = new BarSplit();
			split5.x = 520;
			split5.y = 1;
			_holder.addChild(split5);

			var order:ToolButton = new ToolButton(ToolType.Order, new OrderIcon(0, 0), 9, 5);
			order.addEventListener(MouseEvent.MOUSE_DOWN, tool_mouseDownHandler);
			order.addEventListener(MouseEvent.MOUSE_OVER, tool_mouseOverHandler);
			order.addEventListener(MouseEvent.MOUSE_OUT, tool_mouseOutHandler);
			order.addEventListener(MouseEvent.CLICK, orderButton_clickHandler, false, 0, true);
			order.x = 530;
			order.y = 1;
			_holder.addChild(order);

			var preview:ToolButton = new ToolButton(ToolType.Preview, new PreviewIcon(0, 0), 6, 4);
			preview.addEventListener(MouseEvent.MOUSE_DOWN, tool_mouseDownHandler);
			preview.addEventListener(MouseEvent.MOUSE_OVER, tool_mouseOverHandler);
			preview.addEventListener(MouseEvent.MOUSE_OUT, tool_mouseOutHandler);
			preview.addEventListener(MouseEvent.CLICK, preview_clickHandler, false, 0, true);
			preview.x = 560;
			preview.y = 1;
			_holder.addChild(preview);

			/********************* zoom bar ******************************/
			_zoomGroup = new ZoomGroup();
			_zoomGroup.y = 1;
			addChild(_zoomGroup);


			/************************ extensions bar ***************************/
			_extensionsGroup = new ExtensionsGroup(this);
			_extensionsGroup.y = 1;
			addChild(_extensionsGroup);

			/************************ help bar ***************************/
			_helpGroup = new HelpGroup(this);
			_helpGroup.y = 1;
			addChild(_helpGroup);

			initCardTypeData();

			rePosition();
			
			
			_card = Globals.designoutputCard.card;
			
			setLayer(_card.currentLayer);
			_card.addEventListener( CardEvent.CARD_TYPE_CHANGED, card_cardTypeChanged, false, 0, true);
			_card.addEventListener(CardEvent.CURRENT_LAYER_CHANGED, card_currentLayerChanged, false, 0, true);
		}
		
		protected function card_cardTypeChanged(e:Event):void {
			for (var i:int = 0; i < Globals.designoutputCard.cardTypeCollection.cardTypes.length; i++)
			{
				if(Globals.designoutputCard.cardTypeCollection.cardTypes[i] == Globals.designoutputCard.card.cardType){
					_cardTypesDropDown.Set(String(i));
					break;
				}
			}
			
			setLayer(_card.currentLayer);
		}
		
		private function card_currentLayerChanged(e:CardEvent):void {
			setLayer(_card.currentLayer);
		}
		
		private function setLayer(layer:CardFace):void {
			if(_layer != null){
				_layer.removeEventListener(CardLayerEvent.BACKGROUND_COLOR_CHANGED, layer_backgroundColorChanged, false);
			}
			
			_layer = layer;
			
			if(_layer != null){
				_layer.addEventListener(CardLayerEvent.BACKGROUND_COLOR_CHANGED, layer_backgroundColorChanged, false, 0, true);
				layer_backgroundColorChanged();
			}
			
			_backgroundColorPad.mouseEnabled = _layer && _layer.allowBackgroundColor;
			_backgroundColorPad.alpha = _layer && _layer.allowBackgroundColor ? 1 : 0.5;
		}
		
		protected function layer_backgroundColorChanged(e:Event = null):void {
			_backgroundColorPad.setColor(_layer.getBackgroundColor());
		}
		
		protected function orderButton_clickHandler(e:MouseEvent):void {
			if(Globals.designoutputCard.card.hasPendingChanges){ //Changed
				var messageBox:MessageBox = new MessageBox();
				messageBox.setTitle(ResourceManager.getValue("rm_wantToSave_title"));
				messageBox.setMessage(ResourceManager.getValue("rm_wantToSave_message"));
				messageBox.visibleButtons = MessageBox.YES_NO_CANCEL;
				messageBox.width = 400;
				messageBox.height = 140;
				messageBox.show(true);
				
				messageBox.addEventListener(MessageBoxEvent.OK_YES, saveBeforeOrderDialog_okYesHandler, false, 0, true);
				messageBox.addEventListener(MessageBoxEvent.NO, saveBeforeOrderDialog_noHandler, false, 0, true);
			} else {
				doOrder();
			}
		}
		
		protected function saveBeforeOrderDialog_okYesHandler(e:Event):void {
			var saveDialog:SaveCardDialog = new SaveCardDialog();
			saveDialog.addEventListener(Event.COMPLETE, saveBeforeOrderDialog_completeHandler);
			saveDialog.show(true);
		}
		
		protected function saveBeforeOrderDialog_noHandler(e:Event):void {
			doOrder();
		}
		
		protected function saveBeforeOrderDialog_completeHandler(e:Event):void {
			doOrder();
		}
		
		protected function doOrder():void {
			var request:URLRequest = new URLRequest(Globals.applicationUrl + "order.php");
			var urlParameters:URLVariables = new URLVariables();
			urlParameters["id"] = Globals.designoutputCard.card.cardId;
			request.data = urlParameters;
			navigateToURL(request, "_self");
		}
		
		protected function cutButton_clickHandler(e:MouseEvent):void {
			ClipboardManager.value = Globals.designoutputCard.card.getSelectedItemsXML();
			Globals.designoutputCard.card.deleteSelectElements();
		}
		
		protected function copyButton_clickHandler(e:MouseEvent):void {
			ClipboardManager.value = Globals.designoutputCard.card.getSelectedItemsXML();
		}
		
		protected function pasteButton_clickHandler(e:MouseEvent):void {
			var value:Object = ClipboardManager.value;
			if(value is XML && Globals.designoutputCard.canvas.activeEditor)
				Globals.designoutputCard.canvas.activeEditor.pasteItemsXML((value as XML).*);
		}
		
		private function rePosition():void
		{
			_zoomGroup.x = 600;
			_extensionsGroup.x = 810;
			_helpGroup.x = 915;
		}

		private function initCardTypeData():void
		{
			for (var i:int = 0; i < Globals.designoutputCard.cardTypeCollection.cardTypes.length; i++)
				_cardTypesDropDown.addItem(Globals.designoutputCard.cardTypeCollection.cardTypes[i].name, i + "", i == 0);

			this._cardTypesDropDown.bind();
		}

		/**
		 * Event listener for mouse down on tool buttons
		 * @param evt
		 *
		 */
		private function tool_mouseDownHandler(evt:MouseEvent):void
		{
			this._at = evt.currentTarget as ToolButton;
			if(this._at.isMarked()){
				this._at.Mark(false);
			}
			this._at.Mark(true);
			this._at.addEventListener(MouseEvent.MOUSE_UP, ToolMouseUp);
		}

		private function ToolMouseUp(evt:MouseEvent):void
		{
			var btn:ToolButton = evt.currentTarget as ToolButton;
			btn.Mark(false);
		}
		
		/**
		 * Just make sure the button go back the normal station.
		 * @param evt
		 */		
		private function tool_mouseOutHandler(evt:MouseEvent):void{
			Globals.designoutputCard.hover.hideEvent(evt);
			var btn:ToolButton = evt.currentTarget as ToolButton;
			if(btn.isMarked()){
				btn.Mark(false);
			}
		}

		/**
		 * Change card by choose card type from this cardTypes dropdown
		 * @param evt
		 *
		 */
		private function cardTypesDropDown_changedHandler(evt:Event):void
		{
			var cardIndex:Number = int(_cardTypesDropDown.value.toString());
			_card.changeCardType(cardIndex);
		}

		/**
		 * Change the card background color by chose color from Color picker
		 * @param evt
		 *
		 */
		private function backgroundColorPad_colorChangeHandler(evt:ColorPadEvent):void
		{
			_layer.setBackgroundColor(_backgroundColorPad.color);
		}

		public function backgroundColorPad_mouseDownHandler(evt:MouseEvent):void
		{
			new ColorPicker(Globals.designoutputCard, evt.target as ColorPad).show(true, true);
		}

		public function Resize():void
		{
			this._backgroundBitmap.width = stage.stageWidth;
		}

		/*****************************Tip message show************************************/

		private function showHover(evt:MouseEvent):void
		{
			Globals.designoutputCard.hover.setText(ResourceManager.getValue("rm_chose_card_color"));
		}

		private function tool_mouseOverHandler(evt:MouseEvent):void
		{
			var type:String = (evt.currentTarget as ToolButton).type;
			switch (type)
			{
				case ToolType.Open:
					Globals.designoutputCard.hover.setText(ResourceManager.getValue("rm_open"));
					break;
				case ToolType.Save:
					Globals.designoutputCard.hover.setText(ResourceManager.getValue("rm_save"));
					break;
				case ToolType.Cut:
					Globals.designoutputCard.hover.setText(ResourceManager.getValue("rm_cut"));
					break;
				case ToolType.Copy:
					Globals.designoutputCard.hover.setText(ResourceManager.getValue("rm_copy"));
					break;
				case ToolType.Paste:
					Globals.designoutputCard.hover.setText(ResourceManager.getValue("rm_paste"));
					break;
				case ToolType.Undo:
					Globals.designoutputCard.hover.setText(ResourceManager.getValue("rm_undo"));
					break;
				case ToolType.Redo:
					Globals.designoutputCard.hover.setText(ResourceManager.getValue("rm_redo"));
					break;
				case ToolType.Order:
					Globals.designoutputCard.hover.setText(ResourceManager.getValue("rm_order"));
					break;
				case ToolType.Preview:
					Globals.designoutputCard.hover.setText(ResourceManager.getValue("rm_preview"));
					break;
				case ToolType.Pdf:
					Globals.designoutputCard.hover.setText(ResourceManager.getValue("rm_upload_pdf"));
					break;
				case ToolType.Psd:
					Globals.designoutputCard.hover.setText(ResourceManager.getValue("rm_upload_psd"));
					break;
				case ToolType.Tif:
					Globals.designoutputCard.hover.setText(ResourceManager.getValue("rm_upload_tif"));
					break;
				default:
					break;
			}
		}
		
		protected function open_clickHandler(e:MouseEvent):void {
			if(Globals.designoutputCard.card.hasPendingChanges){ //Changed
				var messageBox:MessageBox = new MessageBox();
				messageBox.setTitle(ResourceManager.getValue("rm_wantToSave_title"));
				messageBox.setMessage(ResourceManager.getValue("rm_wantToSave_message"));
				messageBox.visibleButtons = MessageBox.YES_NO_CANCEL;
				messageBox.width = 400;
				messageBox.height = 140;
				messageBox.show(true);
			
				messageBox.addEventListener(MessageBoxEvent.OK_YES, saveBeforeOpenDialog_okYesHandler, false, 0, true);
				messageBox.addEventListener(MessageBoxEvent.NO, saveBeforeOpenDialog_noHandler, false, 0, true);
			} else {
				doOpen();
			}
		}
		
		private var fileReference:FileReference;
		
		protected function preview_clickHandler(e:MouseEvent):void {
			//Preview sending the PDF file to the server
			/*var request:URLRequest = new URLRequest(Globals.applicationUrl + "preview2.php");
			request.method = URLRequestMethod.POST;
			request.data = Globals.designoutputCard.card.generatePDF();		
			navigateToURL(request, "_blank");*/	
			
			/*
			//Save PDF file locally
			fileReference = new FileReference();
			fileReference.save(Globals.designoutputCard.card.generatePDF(), "card.pdf");*/
			
			
			//Preview using PHP pdf generation
			var request:URLRequest = new URLRequest(Globals.applicationUrl + "preview.php");
			request.method = URLRequestMethod.POST;
						
			var cardXML:XML = Globals.designoutputCard.card.toXML();
			
			var parameters:URLVariables = new URLVariables();
			parameters["cardXML"] = cardXML.toXMLString(); 
			request.data = parameters;
			
			navigateToURL(request, "_blank");
		}
		
		protected function saveBeforeOpenDialog_okYesHandler(e:Event):void {
			var saveDialog:SaveCardDialog = new SaveCardDialog();
			saveDialog.addEventListener(Event.COMPLETE, saveBeforeOpenDialog_completeHandler);
			saveDialog.show(true);
		}
		
		protected function saveBeforeOpenDialog_noHandler(e:Event):void {
			doOpen();
		}
		
		protected function doOpen():void {
			navigateToURL(new URLRequest(Globals.applicationUrl + "cardlog.php"), "_self");
		}
		
		protected function saveBeforeOpenDialog_completeHandler(e:Event):void {
			doOpen();
		}

		protected function saveButton_clickHandler(e:MouseEvent):void {
			var saveDialog:SaveCardDialog = new SaveCardDialog();
			saveDialog.show(true);
		}
	}
}